package cn.shadow.concurrent;

import cn.shadow.message.MessageProcessor;
import com.lmax.disruptor.EventFactory;
import io.netty.buffer.ByteBuf;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Event {
    private static final Logger logger = LoggerFactory.getLogger(Event.class);
    public static final EventFactory<Event> eventFactory = new DefaultEventFactory();
    private Runnable task;
    private ByteBuf buffer;
    private MessageProcessor processor;
    private int moduleID;
    private int sequenceID;

    public Event() {
    }

    /**
     * 如果任务存在，就执行任务，不存在就执行消息发送
     */
    public void handle() {
        if (this.task != null) {
            try {
                this.task.run();
            } catch (Throwable e) {
                logger.error("DisruptorExecutor 处理Runnable出错", e);
            } finally {
                this.task = null;
            }
        } else {
            try {
                this.processor.onMessage(this.buffer, this.moduleID, this.sequenceID);
            } catch (Throwable e) {
                logger.error("处理消息出错, 模块号: " + this.moduleID + ", 序号: " + this.sequenceID, e);
            } finally {
                this.buffer = null;
                this.processor = null;
            }
        }

    }

    public void setEvent(ByteBuf buffer, int moduleID, int sequenceID, MessageProcessor processor) {
        this.buffer = buffer;
        this.processor = processor;
        this.moduleID = moduleID;
        this.sequenceID = sequenceID;
    }

    public void setTask(Runnable task) {
        this.task = task;
    }

    public int getModuleID() {
        return moduleID;
    }

    public void setModuleID(int moduleID) {
        this.moduleID = moduleID;
    }

    public int getSequenceID() {
        return sequenceID;
    }

    public void setSequenceID(int sequenceID) {
        this.sequenceID = sequenceID;
    }
}